<template>
  <el-container>
    <!-- <el-header></el-header> -->
    <el-row>
      <el-col :span="8" class="left-part-content"
        ><div class="grid-content bg-purple">
          <!-- 照片 -->
          <el-card class="box-card user-photo">
            <div slot="header" class="clearfix">
              <span>个性照片</span>&nbsp;<small
                class="tip-photo"
                @click="changePhoto"
                >点击头像即可修改</small
              >
            </div>
            <div>
              <el-upload
                class="avatar-uploader"
                action="https://jsonplaceholder.typicode.com/posts/"
                multiple
                :show-file-list="false"
                :on-preview="handlePictureCardPreview"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
              >
                <img
                  v-if="imageUrl"
                  :src="imageUrl"
                  style="width: 200px; height: 250px"
                  class="avatar"
                />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
              <!-- <el-image
                style="width: 200px; height: 250px"
                :src="user.photo"
                :fit="fit"
              ></el-image> -->
              <!-- <img :src="user.photo" class="image" /> -->
            </div>
          </el-card>
          <!-- 成果统计 -->
          <el-card class="box-card user-progress">
            <div slot="header" class="clearfix">
              <span>数据统计</span>
            </div>
            <div>
              <el-row v-for="item in progressList" :key="item.key">
                <el-col :span="6">{{ item.key }}[{{item.value}}]</el-col>
                <el-col :span="18">
                  <el-progress
                    :text-inside="true"
                    :stroke-width="18"
                    :percentage="item.value"
                    status="success"
                  ></el-progress>
                </el-col>
              </el-row>
            </div>
          </el-card></div
      ></el-col>
      <el-col :span="16" class="right-part-content"
        ><div class="grid-content bg-purple-light">
          <!-- 基本信息 -->
          <el-card class="box-card user-info" v-if="isRouterAlive">
            <div slot="header" class="clearfix">
              <span>基本信息</span>
            </div>
            <div>
              <el-form ref="form" :model="form" label-width="80px">
                <el-row>
                  <el-col :span="8">
                    <el-form-item label="姓名：">
                      <el-input
                        v-model="form.name"
                        :disabled="isEdid"
                      ></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="Email：">
                      <el-input v-model="form.email" disabled></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="Tel：">
                      <el-input v-model="form.tel" :disabled="isEdid"
                        >></el-input
                      >
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="8">
                    <el-form-item label="学院：">
                      <el-select
                        v-model="form.academy"
                        placeholder="请选择所在学院"
                        :disabled="isEdid"
                      >
                        >
                        <el-option
                          v-for="item in this.academyList"
                          :key="item.academyno"
                          :label="item.academyname"
                          :value="item.academyno"
                        ></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="系别：">
                      <el-select
                        v-model="form.depart"
                        placeholder="请选择所在系别"
                        :disabled="isEdid"
                      >
                        >
                        <el-option
                          v-for="item in deptList"
                          :key="item.deptmo"
                          :value="item.deptno"
                          :label="item.deptname"
                        ></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="职称：">
                      <el-input v-model="form.title" :disabled="isEdid"
                        >></el-input
                      >
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="8">
                    <el-form-item label="职工号：">
                      <el-input v-model="form.workno" :disabled="isEdid"
                        >></el-input
                      >
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="年龄：">
                      <el-input v-model="form.age" :disabled="isEdid"
                        >></el-input
                      >
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="性别：">
                      <el-select
                        v-model="form.gender"
                        placeholder="请选择..."
                        :disabled="isEdid"
                        >>
                        <el-option label="男" value="男"></el-option>
                        <el-option
                          label="女"
                          value="女"
                        ></el-option> </el-select
                    ></el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-form-item label="通讯地址">
                    <el-input v-model="form.address" :disabled="isEdid"
                      >></el-input
                    >
                  </el-form-item>
                </el-row>
                <el-form-item>
                  <el-button type="success" @click="onModify"
                    >修改信息</el-button
                  >
                  <el-button type="primary" @click="onSubmit"
                    >保存修改</el-button
                  >
                  <el-button @click="cancelModify">取消保存</el-button>
                </el-form-item>
              </el-form>
            </div>
          </el-card>
          <!-- 个性设置 -->
          <el-card class="box-card quotation">
            <div slot="header" class="clearfix">
              <span>语录</span>
            </div>
            <div>
              <p>
                星空之所以美丽，就是在无限的宇宙中，不管黑暗如何蔓延，都有星星的光芒去把它照亮。
              </p>
              <p>世界也是这样，有绝望的地方，就有希望的产生。</p>
              <p>拥有希望的人，和满天的星星一样，是永远不会孤独的。</p>
              <p>找到和自己一样的星星，把通往自由的路，照亮吧。</p>
              <p><small>Excerpt from：《Star travel notes》</small></p>
            </div>
          </el-card>
        </div></el-col
      >
    </el-row></el-container
  >
</template>

<script>
import * as IndexService from '@/service/index/indexService'
import * as UploadService from "@/service/upload/uploadService"

export default {
  name: 'basicInfo',

  data() {
    return {
      isRouterAlive: true, //组件刷新
      isEdid: true, //控制信息是否可修改
      doUpload: 'doUpload',
      user: {
        photo: require('../../assets/hu.jpg'),
      },
      imageUrl: '',
      fit: 'cover',
      form: {
        name: '',
        email: '',
        tel: '',
        academy: '',
        depart: '',
        title: '',
        workno: '',
        age: '',
        gender: '',
        address: '',
      },
      academyList: [
        //示例数据
        {
          academyno: '10460001',
          academyname: '安全科学与工程学院',
        },
        {
          academyno: '10460002',
          academyname: '能源科学与工程学院',
        },
        {
          academyno: '10460003',
          academyname: '资源环境学院',
        },
      ],
      deptList: [
        //示例数据
        {
          deptno: '10460005001',
          deptname: '测量工程系',
          academyno: '10460005',
          academy: null,
        },
        {
          deptno: '10460005002',
          deptname: '地理信息科学系',
          academyno: '10460005',
          academy: null,
        },
      ],
      progressList: [
        {
          key: '学生指导',
          value: 0,
        },
        {
          key: '教学竞赛',
          value: 0,
        },
        {
          key: '教学获奖',
          value: 0,
        },
        {
          key: '教改项目',
          value: 0,
        },
        {
          key: '教改论文',
          value: 0,
        },
        {
          key: '科研项目',
          value: 0,
        },
        {
          key: '科研奖项',
          value: 0,
        },
        {
          key: '科研论文',
          value: 0,
        },
        {
          key: '出版教材',
          value: 0,
        },
        {
          key: '出版专著',
          value: 0,
        },
        {
          key: '专利申请',
          value: 0,
        },
        {
          key: '软著申请',
          value: 0,
        },
      ],
    }
  },
  watch: {
    //属性监听
    form: {
      handler(newValue, oldValue) {
        //console.log(newValue)
      },
      immediate: true,
      deep: true,
    },
  },
  mounted() {
    //加载学院列表
    IndexService.getAllacademy()
      .then((res) => {
        if (res.data) {
          this.academyList = res.data
        }
      })
      .catch((err) => {
        this.$message.error("加载学院列表信息失败!")
      })
    //加载系别列表
    IndexService.getAllDept().then((res) => {
        if (res.data) {
          this.deptList = res.data
        }
      })
      .catch((err) => {
        this.$message.error("加载系别列表信息失败!")
      })
    //设置用户email信息
    this.form.email = localStorage.getItem('email')
    //根据email获取用户成就信息
    if(this.form.email){
      IndexService.getProgress(this.form.email).then(res=>{
          if(res.data){
            this.progressList=res.data
          }
      }).catch(err=>{
        this.$message.error("加载数据统计信息失败!")
      })
    }


    //根据email获取用户详细信息
    if (this.form.email) {
      IndexService.getUserDeatil(this.form.email).then((res) => {
          //console.log(res.data)
          if (res.data) {
            this.form.name = res.data.name //姓名
            this.form.tel = res.data.tel //联系方式
            this.form.title = res.data.title //职称
            this.form.workno = res.data.workno //职工号
            this.form.age = res.data.age //年龄
            this.form.gender = res.data.gender //性别
            this.form.address = res.data.address //通讯地址
            this.form.depart = res.data.dept.deptno //系别
            this.form.academy = res.data.dept.academy.academyno //学院
          }
        })
        .catch((err) => {
          //console.log(err)
        })
      //获取用户照片
      UploadService.downloadPhoto(this.form.email)
        .then((response) => {
          //解析响应对象
          //console.log(response)
          this.imageUrl =
            'data:image/png;base64,' +
            btoa(
              new Uint8Array(response.data).reduce(
                (data, byte) => data + String.fromCharCode(byte),
                ''
              )
            )
        })
        .catch((error) => {
          // console.log(error)
          this.$message.error("获取个性照片失败!")
        })
    }
  },
  methods: {
    arrayBufferToBase64(buffer) {
      var binary = ''
      var bytes = new Uint8Array(buffer)
      var len = bytes.byteLength
      for (var i = 0; i < len; i++) {
        binary += String.fromCharCode(bytes[i])
      }
      return window.btoa(binary)
    },
    changePhoto() {},
    //修改照片
    handleAvatarSuccess(res, file, fileList) {
      this.imageUrl = URL.createObjectURL(file.raw)
      //获取文件对象
      let imgFile = file.raw
      // console.log(imgFile)
      if (imgFile) {
        //将文件转换为formdata
        let formData = new FormData()
        let email = localStorage.getItem('email')
        formData.append('photo', imgFile) //将文件放入formdata对象
        formData.append('email', email)
        // console.log(formData)
        //开始上传文件
        UploadService.uploadPhoto(formData).then((res) => {
            // console.log(res)
            if (res.data && res.data == 1) {
              //头像更新成功
              this.$message({
                message: '照片更新成功！',
                type: 'success',
              })
            }
          })
          .catch((err) => {
            // console.log(err)
            //更新失败
            this.$message.error('照片更新失败！')
          })
      } else {
        //更新失败
        this.$message.error('照片更新失败！')
      }
    },
    handlePictureCardPreview(file) {
      // console.log(file)
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      //上传头像至服务器
      let fd = new FormData()
      let email = localStorage.getItem('email')
      fd.append('photo', file) //添加图片
      fd.append('email', email) //邮箱参数
      return isJPG && isLt2M
    },
    //修改信息按钮-改变disabled状态
    onModify() {
      //控制表单信息可编辑状态
      this.isEdid = false
    },
    //取消修改信息
    cancelModify() {
      //控制表单信息可编辑状态
      this.isEdid = true
      //刷新页面
      this.$router.go(0)
    },

    //提交信息
    onSubmit() {
      // console.log('submit!')
      //构造userdeail对象
      let userDetail = {
        userid: this.form.email,
        title: this.form.title,
        name: this.form.name,
        workno: this.form.workno,
        deptno: this.form.depart,
        age: this.form.age,
        gender: this.form.gender,
        tel: this.form.tel,
        address: this.form.address,
        // photo: null,
      }
      // console.log(userDetail)
      //提交信息
      IndexService.updateUserDetail(userDetail).then((res) => {
          if (res.data && res.data == 1) {
            //更新成功
            this.$message({
              message: '信息更新成功！',
              type: 'success',
            })
            //控制表单不可编辑
            this.isEdid = true
          } else {
            //更新失败
            this.$message.error('信息更新失败！')
          }
        })
        .catch((err) => {
          // console.log(err)
          //更新失败
          this.$message.error('信息更新失败！')
        })
    },
    onSubmit1() {},
  },
}
</script>
<style scoped>
.el-header {
  /* background-color: blueviolet; */
}
.el-card__header span {
  color: #409eff;
  font-weight: 700;
}
.el-row {
  padding: 20px;
  width: 100%;
}
.left-part-content,
.right-part-content {
  padding: 5px;
}
.left-part-content .el-card,
.right-part-content .el-card {
  margin-bottom: 20px;
}

/* 卡片样式 */
.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: '';
}
.clearfix:after {
  clear: both;
}

.box-card:hover {
  /* width: 480px; */
  box-shadow: 0 5px 15px 0 rgb(0 0 0 / 30%);
}

/* 照片 */
.user-photo {
  width: 100%;
}
.tip-photo {
  color: skyblue;
  text-decoration: underline;
}
.tip-photo:hover {
  color: blue;
  cursor: pointer;
}
.user-photo .el-card__body > div {
  height: 280px;
}
.user-photo .el-card__body > div img {
  width: 60%;
}
.quotation .el-card__body p {
  text-align: left;
  line-height: 1.6rem;
}
.quotation .el-card__body p:last-child {
  text-align: right;
  line-height: 1.6rem;
  font-weight: 700;
  font-family: 'Helvetica Neue', Helvetica, 'PingFang SC', 'Hiragino Sans GB',
    'Microsoft YaHei', '微软雅黑', Arial, sans-serif;
}
/* 成果 */

/* 基本信息 */
.user-info {
  width: 100%;
}
.el-select,
.el-date-editor {
  /* width: 346.5px; */
  width: 100%;
}

/* 上传头像 */
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
